package com.grapevine.contact.util;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;

public class ContactsSearchManager
{

	private String TAG = getClass().getSimpleName();

	private Context mContext;

	private class SearchHandler extends AsyncQueryHandler
	{

		public SearchHandler(ContentResolver cr)
		{
			super(cr);
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor)
		{
			Log.i(TAG, "onQueryComplete");

			super.onQueryComplete(token, cookie, cursor);
		}

	}

	public static final int QUERY_TOKEN = 0x1000;
	public static final int MODE_NORMAL = 0x1001;
	public static final int MODE_FILTER = 0x1002;
	public static final int MODE_STARRED = 0x1003;

	private String[] PROJECTION = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME,
			ContactsContract.Contacts.PHOTO_ID, };

	private String SELECTION = Contacts.HAS_PHONE_NUMBER + " = '1'";

	private String ORDERBY = Contacts.TIMES_CONTACTED + " DESC";

	private int mMode = 0;

	private String mFilter = null;
	private SearchHandler mSearchHandler = new SearchHandler(mContext.getContentResolver());

	public void setMode(int mode)
	{
		mMode = mode;
	}

	public void setFilter(String filter)
	{
		mFilter = filter;
	}

	public void startQuery()
	{
		Uri uri = null;
		mSearchHandler.cancelOperation(QUERY_TOKEN);

		switch (mMode)
		{

		case MODE_NORMAL:
			uri = Contacts.CONTENT_URI;
			mSearchHandler.startQuery(QUERY_TOKEN, null, uri, PROJECTION, SELECTION, null, ORDERBY);
			break;
		case MODE_FILTER:
			uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(mFilter));
			mSearchHandler.startQuery(QUERY_TOKEN, null, uri, PROJECTION, null, null, ORDERBY);
			break;
		case MODE_STARRED:
			uri = Contacts.CONTENT_URI;
			mSearchHandler.startQuery(QUERY_TOKEN, null, uri, PROJECTION, SELECTION + " AND " + Contacts.STARRED + " = '1'", null, ORDERBY);
			break;
		}

	}
}